package com.yuncheng.spcyApi.busService.exam.service;

import com.yuncheng.spcyApi.busService.exam.constant.DefaultQuestionRuleEnum;
import com.yuncheng.spcyApi.busService.exam.constant.JudgementTypeEnum;
import com.yuncheng.spcyApi.busService.exam.constant.QuestionTypeEnum;
import com.yuncheng.spcyApi.busService.exam.vo.ParseQuestionRules;
import com.yuncheng.spcyApi.busService.exam.vo.QuestionInfoVo;
import com.yuncheng.spcyApi.constant.other.PxSjConstant;
import com.yuncheng.spcyApi.entity.SpcyPxSjtm;
import com.yuncheng.spcyApi.entity.SpcyPxSjtmxx;
import com.yuncheng.spcyApi.service.ISpcyPxSjtmService;
import com.yuncheng.spcyApi.service.ISpcyPxSjtmxxService;
import com.yuncheng.spcyApi.utils.GetUuIdUtils;
import com.yuncheng.spcyApi.utils.LocalFileUploadUtils;
import com.yuncheng.vo.HttpResult;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import utils.Util;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author hua
 */
@Service
public class ParseQuestionTextService {

    private static final Logger log = LoggerFactory.getLogger(ParseQuestionTextService.class);

    @Resource
    private ISpcyPxSjtmService spcyPxSjtmService;

    @Resource
    private ISpcyPxSjtmxxService spcyPxSjtmxxService;

    @Resource
    private LocalFileUploadUtils localFileUploadUtils;

    /*public static void main(String[] args) {
        String url = "D:/下载/试卷(1).docx";
        analyze(getWordText(url, Util.getWjHz(url)));
    }*/

    /**
     * 根据试卷文档生成题目-根据试卷id
     * (目前支持 单选、多选、判断题型)
     * */
    public HttpResult analyzeSjWord(MultipartFile uploadFile, String sjid){
        if (uploadFile == null){
            return HttpResult.error("请上传文件！");
        }

        if (StringUtils.isBlank(sjid)){
            return HttpResult.error("试卷参数为空！");
        }

        String wjHz = Util.getWjHz(uploadFile.getOriginalFilename());
        if (!(wjHz.equals(".docx") || wjHz.equals(".doc"))){
            return HttpResult.error("请上传[.docx]/[.doc]文件！");
        }

        File fileUpload = localFileUploadUtils.uploadDempFile(uploadFile, uploadFile.getOriginalFilename());

        List<QuestionInfoVo> questionInfoVoList = analyzeWordText(getWordText(fileUpload.getAbsolutePath(), wjHz));

        List<SpcyPxSjtm> sjtmList = new ArrayList<>();
        List<SpcyPxSjtmxx> sjtmxxList = new ArrayList<>();
        int order = 1;
        for (QuestionInfoVo questionInfoVo : questionInfoVoList){

            SpcyPxSjtm sjtm = new SpcyPxSjtm();
            sjtm.setId(GetUuIdUtils.ReplaceUuId());
            sjtm.setFxh(order);
            sjtm.setFsjid(sjid);
            sjtm.setFtmfs(questionInfoVo.getScore());

            if (questionInfoVo.getType() == QuestionTypeEnum.COMPLETION){
                continue;
            }

            if (questionInfoVo.getType() == QuestionTypeEnum.SUBJECTIVE) {
                sjtm.setFtmlx(QuestionTypeEnum.JUDGMENTAL.getLabel());
            }else {
                sjtm.setFtmlx(questionInfoVo.getType().getLabel());
            }
            sjtm.setFsjtm(sjtm.getFxh() + "." + questionInfoVo.getContent());

            sjtmList.add(sjtm);

            if (questionInfoVo.getType() == QuestionTypeEnum.SIGNAL_CHOICE
                    || questionInfoVo.getType() == QuestionTypeEnum.MULTIPLE_CHOICE){
                for (int i = 0; i < questionInfoVo.getOptions().size(); i++) {
                    SpcyPxSjtmxx sjtmxx = new SpcyPxSjtmxx();
                    sjtmxx.setId(GetUuIdUtils.ReplaceUuId());
                    sjtmxx.setFsjtmid(sjtm.getId());
                    sjtmxx.setFxh(i+1);

                    sjtmxx.setFsjtmxx(ParseQuestionTextUtils.letterList[i] + "." + questionInfoVo.getOptions().get(i).getContent());
                    sjtmxx.setFsfzqda(
                            StringUtils.isNotBlank(questionInfoVo.getOptions().get(i).getAnswer())
                            ? PxSjConstant.SJTM_DJDA_SFZQDA_YES
                            : PxSjConstant.SJTM_DJDA_SFZQDA_NO);

                    sjtmxxList.add(sjtmxx);
                }
            }else {

                SpcyPxSjtmxx sjtmxx1 = new SpcyPxSjtmxx();
                SpcyPxSjtmxx sjtmxx2 = new SpcyPxSjtmxx();

                JudgementTypeEnum zqda = JudgementTypeEnum.CW;
                if (questionInfoVo.getOptions().size() > 0){
                    String answer = questionInfoVo.getOptions().get(0).getAnswer();
                    if (StringUtils.isNotBlank(answer) && answer.contains(JudgementTypeEnum.ZQ.getType())) {
                        zqda = JudgementTypeEnum.ZQ;
                    }
                }

                if (zqda == JudgementTypeEnum.ZQ) {
                    sjtmxx1.setFsfzqda(PxSjConstant.SJTM_DJDA_SFZQDA_YES);
                    sjtmxx2.setFsfzqda(PxSjConstant.SJTM_DJDA_SFZQDA_NO);
                } else {
                    sjtmxx1.setFsfzqda(PxSjConstant.SJTM_DJDA_SFZQDA_NO);
                    sjtmxx2.setFsfzqda(PxSjConstant.SJTM_DJDA_SFZQDA_YES);
                }

                sjtmxx1.setId(GetUuIdUtils.ReplaceUuId());
                sjtmxx1.setFsjtmid(sjtm.getId());
                sjtmxx1.setFxh(1);
                sjtmxx1.setFsjtmxx(JudgementTypeEnum.ZQ.getType());

                sjtmxx2.setId(GetUuIdUtils.ReplaceUuId());
                sjtmxx2.setFsjtmid(sjtm.getId());
                sjtmxx2.setFxh(2);
                sjtmxx2.setFsjtmxx(JudgementTypeEnum.CW.getType());

                sjtmxxList.add(sjtmxx1);
                sjtmxxList.add(sjtmxx2);
            }

            order++;
        }

        spcyPxSjtmService.saveBatch(sjtmList);
        spcyPxSjtmxxService.saveBatch(sjtmxxList);

        fileUpload.delete();
        return HttpResult.ok("操作成功");
    }

    /**
     * 获取文档里面的内容
     * @param absUrl 绝对路径
     * @param formart 文档类型
     * @return
     */
    private String getWordText(String absUrl, String formart){
        File file = new File(absUrl);
        if (!file.exists()){
            return "";
        }

        FileInputStream fis = null;
        XWPFDocument document = null;
        XWPFWordExtractor extractor = null;
        String msg = "";
        try {
            fis = new FileInputStream(file);
            if (formart.equals(".docx")) {
                document = new XWPFDocument(fis);
                extractor = new XWPFWordExtractor(document);
                msg = extractor.getText();
                extractor.close();
                document.close();
            }else if (formart.equals(".doc")){
                WordExtractor ex = new WordExtractor(fis);
                msg = ex.getText();
                ex.close();
            }else {
                log.info("该文件不是word文件【{}】",formart);
            }
        } catch (Exception e) {
            log.error("获取【{}】类型的word文档内容出错-{}",formart,e);
        }finally {
            try {
                fis.close();
            } catch (IOException e) {
                log.error("关闭文件出错【IOException】-{}",e);
            }
        }

        return msg;
    }

    /** 解析内容 */
    private List<QuestionInfoVo> analyzeWordText(String questionsText){
        ParseQuestionRules rule = DefaultQuestionRuleEnum.CHAOXING.getRule();

        /*rule.setDivisionRule("\\n\\d{1,3}\\s*[\\.、：:]");
        rule.setQuestionRule("");
        rule.setAnswerRule("答案：\\s*([\\s\\S]*)");
        rule.setAnswerSplit("；");
        rule.setOptionRule("\\n\\s*[A-Z]\\s*[、.]\\s*");*/

//        rule.setOptionRule("([A-Z]、[^A-Z]*?)(?=[A-Z]、|$)");

        //将富文本换行改成\n
//        String text = questionsText.replaceAll("<br\\/?>","\n");

        // 去除富文本最外层p
//        text = text.replaceAll("<p>|<\\/p>","");

        return ParseQuestionTextUtils.parse(questionsText, rule);
    }

    /** 解析内容模板 */
    private String getQuestionStr(){

        /**
         * 一、单选题（每题1分）
         * 二、多选题（每题2分）
         * 三、判断题（每天3分）
         */
        return
                "1.下列说法中正确的是( )。\n" +
                        "A.20 世纪 50 年代提出了软件工程概念\n" +
                        "B.20 世纪 60 年代提出了软件工程概念\n" +
                        "C.20 世纪 70 年代出现了客户机/服务器技术\n" +
                        "D.20 世纪 80 年代软件工程学科达到成熟\n" +
                        "答案： B\n" +
                        "2.软件危机的主要原因是( )。\n" +
                        "A.软件工具落后\n" +
                        "B.软件生产能力不足\n" +
                        "C.对软件的认识不够\n" +
                        "D.软件本身的特点及开发方法\n" +
                        "答案： D" +
                        "\n3.软件是概念()\n答案：正确";
    }
}
